package com.library.controller;

import com.library.model.Staff;
import com.library.service.StaffService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/api/staff")
public class StaffController {

    private final StaffService staffService;

    public StaffController(StaffService staffService) {
        this.staffService = staffService;
    }


    @GetMapping
    public ResponseEntity<List<Staff>> getAllStaff() {
        List<Staff> staffList = staffService.getAllStaff();
        return ResponseEntity.ok(staffList);
    }


    @GetMapping("/search")
    public ResponseEntity<List<Staff>> searchStaff(@RequestParam Map<String, Object> criteria) {
        List<Staff> staffList = staffService.getStaffByCriteria(criteria);
        return ResponseEntity.ok(staffList);
    }


    @GetMapping("/{id}")
    public ResponseEntity<Staff> getStaffById(@PathVariable Long id) {
        Staff staff = staffService.getStaffById(id);
        if (staff != null) {
            return ResponseEntity.ok(staff);
        } else {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
        }
    }


    @GetMapping("/employee-id/{employeeId}")
    public ResponseEntity<Staff> getStaffByEmployeeId(@PathVariable String employeeId) {
        Staff staff = staffService.getStaffByEmployeeId(employeeId);
        if (staff != null) {
            return ResponseEntity.ok(staff);
        } else {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
        }
    }


    @PostMapping
    public ResponseEntity<String> addStaff(@RequestBody Staff staff) {
        boolean isAdded = staffService.addStaff(staff);
        if (isAdded) {
            return ResponseEntity.status(HttpStatus.CREATED).body("员工添加成功");
        } else {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("员工编号已存在");
        }
    }


    @PutMapping("/{id}")
    public ResponseEntity<String> updateStaff(@PathVariable Long id, @RequestBody Staff staff) {
        // 确保ID一致
        staff.setId(id);
        boolean isUpdated = staffService.updateStaff(staff);
        if (isUpdated) {
            return ResponseEntity.ok("员工信息更新成功");
        } else {
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body("员工不存在或员工编号已被使用");
        }
    }


    @DeleteMapping("/{id}")
    public ResponseEntity<String> deleteStaff(@PathVariable Long id) {
        boolean isDeleted = staffService.deleteStaff(id);
        if (isDeleted) {
            return ResponseEntity.ok("员工删除成功");
        } else {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("员工不存在");
        }
    }
}
